package com.lzdongrui.backend.service.impl;

import java.util.List;

import com.lzdongrui.backend.domain.College;
import com.lzdongrui.backend.domain.Grade;
import com.lzdongrui.backend.domain.Major;
import com.lzdongrui.backend.domain.dto.MajorDTO;
import com.lzdongrui.backend.domain.dto.StudentinfoDTO;
import com.lzdongrui.backend.domain.vo.StudentinfoVO;
import com.lzdongrui.backend.mapper.GradeMapper;
import com.lzdongrui.common.constant.CacheConstants;
import com.lzdongrui.common.core.domain.entity.SysRole;
import com.lzdongrui.common.core.domain.entity.SysUser;
import com.lzdongrui.common.exception.ServiceException;
import com.lzdongrui.common.utils.DateUtils;
import com.lzdongrui.common.utils.SecurityUtils;
import com.lzdongrui.common.utils.StringUtils;
import com.lzdongrui.common.utils.bean.BeanValidators;
import com.lzdongrui.common.utils.snowid.SnowflakeIdWorker;
import com.lzdongrui.system.mapper.SysRoleMapper;
import com.lzdongrui.system.service.ISysConfigService;
import com.lzdongrui.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lzdongrui.backend.mapper.StudentinfoMapper;
import com.lzdongrui.backend.domain.Studentinfo;
import com.lzdongrui.backend.service.IStudentinfoService;

import javax.validation.Validator;

/**
 * 学生信息Service业务层处理
 * 
 * @author hjs
 * @date 2023-05-05
 */
@Service
public class StudentinfoServiceImpl implements IStudentinfoService 
{
    private static final Logger log = LoggerFactory.getLogger(StudentinfoServiceImpl.class);

    @Autowired
    private StudentinfoMapper studentinfoMapper;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    protected Validator validator;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private GradeMapper gradeMapper;

    /**
     * 查询学生信息
     * 
     * @param id 学生信息主键
     * @return 学生信息
     */
    @Override
    public Studentinfo selectStudentinfoById(Long id)
    {
        return studentinfoMapper.selectStudentinfoById(id);
    }

    /**
     * 查询学生信息列表
     * 
     * @param studentinfo 学生信息
     * @return 学生信息
     */
    @Override
//    public List<Studentinfo> selectStudentinfoList(StudentinfoDTO studentinfo)
    public List<StudentinfoVO> selectStudentinfoList(StudentinfoDTO studentinfo)
    {
        return studentinfoMapper.selectStudentinfoList(studentinfo);
    }

    /**
     * 新增学生信息
     * 
     * @param studentinfo 学生信息
     * @return 结果
     */
    @Override
    public int insertStudentinfo(Studentinfo studentinfo)
    {
        Studentinfo n = studentinfoMapper.selectStudentInfoOne(studentinfo);
        if (!StringUtils.isNull(n)) {
            throw new ServiceException("该学号已存在！");
        }
        studentinfo.setId(snowflakeIdWorker.nextId());
        studentinfo.setIsAtSchool(0);
        String configKey = sysConfigService.selectConfigByKey(CacheConstants.USER_PASSWORD_PROFIX);
        studentinfo.setPassword(SecurityUtils.encryptPassword(configKey+studentinfo.getSno()));
        studentinfo.setCreateTime(DateUtils.getNowDate());
        String x = sysConfigService.selectConfigByKey(CacheConstants.STUDENT_ROLE_KEY);
        SysRole sysRole = sysRoleMapper.selRoleKey(sysConfigService.selectConfigByKey(CacheConstants.STUDENT_ROLE_KEY));
        sysUserService.addUserRole(studentinfo.getId(),sysRole.getRoleId());
        return studentinfoMapper.insertStudentinfo(studentinfo);
    }

    /**
     * 修改学生信息
     * 
     * @param studentinfo 学生信息
     * @return 结果
     */
    @Override
    public int updateStudentinfo(Studentinfo studentinfo)
    {
        studentinfo.setUpdateTime(DateUtils.getNowDate());
        return studentinfoMapper.updateStudentinfo(studentinfo);
    }

    /**
     * 批量删除学生信息
     * 
     * @param ids 需要删除的学生信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentinfoByIds(Long[] ids)
    {
        return studentinfoMapper.deleteStudentinfoByIds(ids);
    }

    /**
     * 删除学生信息信息
     * 
     * @param id 学生信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentinfoById(Long id)
    {
        return studentinfoMapper.deleteStudentinfoById(id);
    }

    /**
     * 导入学生
     *
     * @param studentinfos
     * @param updateSupport
     * @return
     */
    @Override
    public String importStudentinfo(List<Studentinfo> studentinfos, boolean updateSupport) {
        if (StringUtils.isNull(studentinfos) || studentinfos.size() == 0) {
            throw new ServiceException("导入学生数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Studentinfo studentinfo : studentinfos) {
            try {
                //查询班级数据是否存在
                Grade gradeInfo = gradeMapper.selectGradeByName(studentinfo.getGradeName());
                if(!StringUtils.isNull(gradeInfo)){
                    //查询学生的数据是否有重复（学号）
                    Studentinfo n = studentinfoMapper.selectStudentInfoOne(studentinfo);
                    if (StringUtils.isNull(n)) {
                        studentinfo.setId(snowflakeIdWorker.nextId());
                        studentinfo.setGradeId(gradeInfo.getId());
                        BeanValidators.validateWithException(validator, studentinfo);
                        this.insertStudentinfo(studentinfo);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、学号 " + studentinfo.getSno() + "、姓名 " + studentinfo.getName() + " 导入成功");
                    } else if (updateSupport) {
                        studentinfo.setGradeId(gradeInfo.getId());
                        BeanValidators.validateWithException(validator, studentinfo);
                        this.updateStudentinfo(studentinfo);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、学号 " + studentinfo.getSno() + "、姓名 " + studentinfo.getName() + " 更新成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、学号 " + studentinfo.getSno() + "、姓名 " + studentinfo.getName() + " 已存在");
                    }
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学院Code " + studentinfo.getGradeName() + " 不存在");
                }
                //返回异常数据
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学号 " + studentinfo.getSno() + "、姓名 " + studentinfo.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
